package com.hospital.servlet;

import com.hospital.dao.DoctorDAO;
import com.hospital.model.Doctor;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(urlPatterns = {"/api/doctors", "/api/doctors/*"})
public class DoctorServlet extends HttpServlet {
    private DoctorDAO doctorDAO = new DoctorDAO();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        
        String pathInfo = request.getPathInfo();
        PrintWriter out = response.getWriter();
        
        if (pathInfo == null || pathInfo.equals("/")) {
            // 获取科室医生列表
            String departmentId = request.getParameter("departmentId");
            if (departmentId != null) {
                List<Doctor> doctors = doctorDAO.findByDepartment(Integer.parseInt(departmentId));
                writeJsonArray(out, doctors);
            } else {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                out.print("{\"error\":\"Missing departmentId parameter\"}");
            }
        } else {
            // 获取单个医生信息
            String[] splits = pathInfo.split("/");
            if (splits.length == 2) {
                Integer doctorId = Integer.parseInt(splits[1]);
                Doctor doctor = doctorDAO.findById(doctorId);
                if (doctor != null) {
                    writeJsonObject(out, doctor);
                } else {
                    response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                    out.print("{\"error\":\"Doctor not found\"}");
                }
            }
        }
    }
    
    private void writeJsonArray(PrintWriter out, List<Doctor> doctors) {
        out.print("[");
        for (int i = 0; i < doctors.size(); i++) {
            Doctor doctor = doctors.get(i);
            writeJsonObject(out, doctor);
            if (i < doctors.size() - 1) {
                out.print(",");
            }
        }
        out.print("]");
    }
    
    private void writeJsonObject(PrintWriter out, Doctor doctor) {
        out.print("{");
        out.print("\"id\":" + doctor.getId() + ",");
        out.print("\"name\":\"" + doctor.getName() + "\",");
        out.print("\"title\":\"" + (doctor.getTitle() != null ? doctor.getTitle() : "") + "\",");
        out.print("\"status\":" + doctor.getStatus() + ",");
        out.print("\"department\":{");
        out.print("\"id\":" + doctor.getDepartment().getId() + ",");
        out.print("\"name\":\"" + doctor.getDepartment().getName() + "\"");
        out.print("}");
        out.print("}");
    }
}